package com.skstudio.nuprint.lpd;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class LpdSerial {
	public static final String cCommandSync = "XXXX";
	
	FileOutputStream mFos = null;
	FileInputStream mFis = null;
	
	public LpdSerial(File fs, boolean read) {
		try{
			if (read) {
				mFis = new FileInputStream(fs);
			} else {
				mFos = new FileOutputStream(fs, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void close() {				
		try {
			if (mFis != null) mFis.close();
		} catch (IOException e) {

			e.printStackTrace();
		}
	
		try {
			if (mFos != null) mFos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		mFis = null;
		mFos = null;
	}
	
	public void writeCommand(byte[] command)  {
		if (command == null) return;
		
		try {
			byte[] head = cCommandSync.getBytes();
			mFos.write(head);
			
			int size = command.length;
			mFos.write(ByteBuffer.allocate(4).putInt(size).array());
			
			mFos.write(command);
			
			mFos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public byte[] readCommand()  {
		try {
			if (mFis.available() == 0) return null;
			
			byte[] head = new byte[cCommandSync.getBytes().length];
			mFis.read(head);
			if (!Arrays.equals(head, cCommandSync.getBytes())) return null;
			
			head = new byte[4];
			mFis.read(head); 
			int size = ByteBuffer.wrap(head).getInt();
			
			byte[] command = new byte[size];
			mFis.read(command);
			return command;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
